home *** CD-ROM | disk | FTP | other *** search
- Path: erich.triumf.ca!bennett
- From: bennett@erich.triumf.ca (P.Bennett)
- Newsgroups: comp.lang.c
- Subject: Re: gets() question
- Date: 7 Jan 1996 09:44 PST
- Organization: TRIUMF: Tri-University Meson Facility
- Distribution: world
- Message-ID: <7JAN199609444189@erich.triumf.ca>
- References: <4cosgf$rir@newsbf02.news.aol.com>
- NNTP-Posting-Host: erich.triumf.ca
- News-Software: VAX/VMS VNEWS 1.50
-
- In article <4cosgf$rir@newsbf02.news.aol.com>, simpsondg@aol.com (SimpsonDG) writes...
- >Can any of you C gurus out there help me with this? I have a problem with
- >gets() that I don't understand. The program below will successfully input
- >the string s[0], but will simply ignore the gets() that inputs s[1] and
- >goes on to ask for i[1]. What's the deal? A little experimenting seems
- >to indicate that the problem arises when I have a gets() following a
- >scanf() -- e.g., a program using only gets() or only scanf() works fine.
- >
-
- >#include "stdio.h"
- >
- >void main(void)
-
- To avoid flames in comp.lang.c (and because the C standard says so), this _must
- be:
- int main(void)
- in spite of many books to the contrary.
- (then you need "return 0;" at the end of main() )
-
- Unless you are careful with the first argument to scanf(), it will leave a
- newline in the input buffer. If you use only scanf()s, this is no problem, as
- the next scanf() will consider the newline as "white space" and just read past
- it. However, most other input functions will just read up to, and including, a
- newline, so seem to be ignored following a scanf().
-
- A better input method is to _only_ use fgets() (_never_ gets()!), then use
- sscanf(), strtok(), atoi(), or whatever to parse the input - this avoids the
- problem you are having, and allows you to do some defensive coding, to catch
- invalid input. If the user enters something shorter than the buffer size
- specified for fgets(), fgets() will leave a '\n' at the end, which you may need
- to remove...
-
- gets() should not be used because it allows the user to enter an infinitely
- long string, and write far beyond the space you allocated for input, which will
- corrupt other variables or code.
-
-
- >{
- > int i[5];
- > char s[3][10];
- >
- > printf ("Enter s[0]: ");
- > gets (s[0]);
- >
- > printf ("Enter i[0]]: ");
- > scanf ("%d",&i[0]);
- >
- > printf ("Enter s[1]: ");
- > gets (s[1]); /* this gets() doesn't wait for input */
- >
- > printf ("Enter i[1]]: ");
- > scanf ("%d",&i[1]);
- >}
- Peter Bennett VE7CEI | Vessels shall be deemed to be in sight
- Internet: bennett@triumf.ca | of one another only when one can be
- Packet: ve7cei@ve7kit.#vanc.bc.ca | observed visually from the other
- TRIUMF, Vancouver, B.C., Canada | ColRegs 3(k)
- GPS and NMEA info and programs: ftp://sundae.triumf.ca/pub/peter/index.html
-
-